package cn.neosoft.apigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpRequest;
import org.apache.http.protocol.RequestContent;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

@Component
public class LoginFilter extends ZuulFilter {
    //pre类型filter 前置
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    //过滤器数字越小越先执行
    @Override
    public int filterOrder() {
        return 4;
    }

    //过滤器是否生效
    @Override
    public boolean shouldFilter() {
        //request
        RequestContext requestContent = RequestContext.getCurrentContext();
        HttpServletRequest request=requestContent.getRequest();

        //gateway/order/api/v1/order/save
        //http://localhost:9000/gateway/order/api/v1/order/save

        System.out.println(request.getRequestURI());
        System.out.println(request.getRequestURL());

        //只有gateway/order/api/v1/order/save 时使这个生效
        if("/gateway/order/api/v1/order/save".equalsIgnoreCase(request.getRequestURI())){
            return true;
        }else{
            return false;
        }

    }

    //业务逻辑
    @Override
    public Object run() throws ZuulException {

        System.out.println("已经拦截");
        //request
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request=requestContext.getRequest();

        String token = request.getHeader("token");
        String cookie = request.getHeader("cookie");

        if(StringUtils.isBlank(token)){
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }

        return null;
    }
}
